import { Component, OnInit } from '@angular/core';
import { Singlepage } from '../../model/singlepage';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { SinglepageService } from '../../service/singlepage.service';
import { ConfigService } from '../../service/config.service';

@Component({
  selector: 'app-editpage',
  templateUrl: './editpage.component.html',
  styleUrls: ['./editpage.component.css']
})
export class EditpageComponent implements OnInit {

  singlepage:Singlepage;
  parm:string;
  selectedFile:string;

  constructor(
    private http:HttpClient,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private singlepageservice:SinglepageService,
    private configservice:ConfigService
  ) {
    this.singlepage=new Singlepage();
    this.parm=this.routerinfo.snapshot.params['id'];
   }

  ngOnInit() {
    if(this.parm=='add'){
      this.singlepage=new Singlepage();
    }else{
      this.getSinglepage(this.parm);
    }
  }
  private  getSinglepage(id:string){
    this.singlepageservice.getSinglepage(id)
    .then((data:any)=>{
      if(data){
        this.singlepage=data;
      }
      else{
        alert("修改异常，请刷新后重试！");
      }
      
    })

  }

  save(){
    this.singlepageservice.addSinglepage(this.singlepage)
    .then((flag:boolean)=>{
      if(flag==true){
        this.goBack();
      }
      else{
        alert('失败');
      }
    })
  
  }

  goBack(){
    this.router.navigate(['showlist']);
  }

  onFileChanged(event) {
    this.selectedFile = event.target.files[0];
  }

  onUpload() {
    const uploadData = new FormData();
  uploadData.append('file', this.selectedFile);

  this.http.post(this.configservice.host+'/manage/uploadFile',uploadData).subscribe(
    (data:any)=>{
      //alert(data);
      //console.log(JSON.stringify(data));
      //  let host="https://119.23.28.201/public/";
      //  this.singlepage.img=host+data.pic;
      this.singlepage.img=data.pic;


    },(err:HttpErrorResponse)=>{
      console.log(err.message);
    }
  )

  }


}

